﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#ifndef CellNonblockingAcceptor_h
#define CellNonblockingAcceptor_h

#include "CellPrerequisites.h"
#include "CellMessageAcceptor.h"
#include "CellSession.h"
#include "CellThread.h"

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/event.h>

namespace cell
{
/// 线程前置声明
class NonblockingAcceptorThread;
/// Session 前置声明
class NonblockingAcceptorSession;
/// 工作器
class NonblockingWorker;

#define NBA_BUFFER_SIZE 8192


/** 非阻塞消息接收器。
@author
	Jiangwei Xu
*/
class _CellExport NonblockingAcceptor : public MessageAcceptor, public GeneralAlloc
{
public:
	/**
	*/
	NonblockingAcceptor(void);

	/**
	*/
	virtual ~NonblockingAcceptor(void);

public:
	/** 绑定消息接收服务到指定端口。
	*/
	bool bind(uint port);

	/** 绑定消息接收服务到指定地址。
	*/
	bool bind(const InetAddress& addr);

	/** 解绑当前绑定的服务地址。
	*/
	void unbind(void);

	/** 关闭指定会话。
	*/
	void close(Session* session);

	/** 列举所有会话。
	*/
	void listSessionIds(SessionIdList& list);

	/** 返回指定 ID 的 Session
	*/
	Session* getSession(ulong id);

	/** 设置最大连接数。
	*/
	void setMaxConnectNum(int num);

	/** 返回最大连接数。
	*/
	int getMaxConnectNum(void);

	/** 返回当前连接数。
	*/
	int getConnectNum(void);

public:
	/** 向指定的会话写入消息。
	*/
	void write(Session* session, Message* message);

	/** 从指定的会话读取消息。
	*/
	void read(Message* message, Session* session);

public:
	/**
	*/
	void setTimeout(int timeInSeconds);

	/**
	*/
	uint getPort(void) const;

protected:
	/**
	*/
	NonblockingAcceptorSession* findSession(evutil_socket_t fd);

	/**
	*/
	void present(NonblockingAcceptorSession* session);

private:

	/**
	*/
	NonblockingAcceptorSession* fireSessionCreated(socket_t socket, const char* host, const uint port);

	/**
	*/
	void fireSessionDestroyed(NonblockingAcceptorSession* session);

	/**
	*/
	void fireSessionOpened(NonblockingAcceptorSession* session);

	/**
	*/
	void fireSessionClosed(NonblockingAcceptorSession* session);

	/**
	*/
	void fireMessageReceived(NonblockingAcceptorSession* session, Message* message);

	/**
	*/
	void fireMessageSent(NonblockingAcceptorSession* session, Message* message);

	/**
	*/
	void fireErrorOccurred(uint16 errorCode, NonblockingAcceptorSession* session);

	/**
	*/
	void clearSessions(void);

private:
	int mMaxConnectNum;
	int mCurrentConnectNum;
	uint mPort;

	timeval mSessionTimeout;

	CELL_MUTEX(mMonitor);

	evutil_socket_t mListener;
	struct event_base* mBase;
	struct event* mListenerEvent;

	NonblockingAcceptorThread* mDispatchThread;

	CELL_MUTEX(mSessionMutex);
	typedef HashMap<evutil_socket_t, NonblockingAcceptorSession*> SessionMap;
	typedef std::vector<NonblockingAcceptorSession*> SessionList;
	SessionMap mSessions;
	SessionList mDesertedSessions;

	CELL_MUTEX(mWorkerMutex);
	typedef std::vector<NonblockingWorker*> WorkerList;
	WorkerList mWorkers;

	friend class NonblockingAcceptorThread;
	friend class NonblockingAcceptorSession;
	friend class NonblockingWorker;

	friend void listener_cb(evutil_socket_t listener, short event, void *arg);
	friend void read_cb(struct bufferevent *bev, void *arg);
	friend void write_cb(struct bufferevent *bev, void *arg);
	friend void event_cb(struct bufferevent *bev, short event, void *arg);
};


/** Nonblocking acceptor session
*/
class _CellPrivate NonblockingAcceptorSession : public Session
{
public:
	/**
	*/
	NonblockingAcceptorSession(NonblockingAcceptor* acceptor,
		socket_t socket, const InetAddress& address);
	/**
	*/
	virtual ~NonblockingAcceptorSession(void);

public:
	socket_t socket;
	bufferevent* bev;
	uint64 desertedTime;

	bool closed;
	bool bevClosed;

	CELL_MUTEX(writeMutex);

public:
	/**
	*/
	void pushBuf(char* data, int len);

	/**
	*/
	void notifyRead(void);

private:
	/**
	*/
	int popBuf(char* data);

private:
	/**
	*/
	void processRecv(char* data, int size);
	/**
	*/
	int extractData(char* data, const int size);

private:
	CELL_MUTEX(mQueueMutex);

	NonblockingAcceptor* mAcceptor;

	std::list<char*> mDataQueue;
	std::list<int> mLengthQueue;
	std::list<char*> mDeserted;

	char mCache[NBA_BUFFER_SIZE];
	int mCacheCursor;
};

/**
*/
class _CellPrivate NonblockingWorker : public Thread
{
public:
	/**
	*/
	NonblockingWorker(NonblockingAcceptor* acceptor);
	/**
	*/
	virtual ~NonblockingWorker(void);

public:
	/**
	*/
	void run(void);

	/**
	*/
	void stop(void);

public:
	/**
	*/
	void management(NonblockingAcceptorSession* session);

	/**
	*/
	bool unmanagement(NonblockingAcceptorSession* session);

	/**
	*/
	bool has(NonblockingAcceptorSession* session);

	/**
	*/
	void tread(void);

	/**
	*/
	int capacity(void);

private:
	NonblockingAcceptor* mAcceptor;
	bool mSpinning;

	typedef std::vector<NonblockingAcceptorSession*> SessionList;
	SessionList mSessions;

	CELL_MUTEX(mMutex);
	CELL_MUTEX(mSessionMutex);
	CELL_THREAD_SYNCHRONISER(mWorkSync);
};


// Event2 Callback function define
void listener_cb(evutil_socket_t listener, short event, void *arg);
void read_cb(struct bufferevent *bev, void *arg);
void write_cb(struct bufferevent *bev, void *arg);
void event_cb(struct bufferevent *bev, short event, void *arg);

} // end namespace cell

#endif // CellNonblockingAcceptor_h
